package com.hr.baseUtil;

import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.word.WordExportUtil;
import com.base.dao.model.BFile;
import com.base.dao.model.Ret;
import com.base.date.DateUtil;
import com.base.io.FileUtil;
import com.base.lang.Base64;
import com.base.service.BFileService;
import com.hr.HrConstants;
import com.hr.dao.model.Contract;
import com.hr.dao.model.ContractPath;
import com.hr.daoEx.model.ContractEx;
import com.hr.service.ContractPathService;
import com.hr.service.ContractService;
import com.item.ConstantsCode;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static org.aspectj.weaver.tools.cache.SimpleCacheFactory.path;

@RequestMapping("/baseUtil")
@Controller
public class Base64UtilController {
    @Autowired
    private BFileService bFileService;
    @Autowired
    private ContractService contractService;
    @Autowired
    private ContractPathService contractPathService;

    @RequestMapping("/base64")
    @ResponseBody
    public Ret getBase64(String media, Contract contract) {

        //查询合同
        Contract record = contractService.selectByPrimaryKey(contract.getId());
        if(null == record){
            Ret ret = new Ret();
            ret.setCode(-1);
            ret.setMsg("合同不存在");
            return ret;
        }
        //查询是否已经签署过
        if(0 != record.getType()){
            Ret ret = new Ret();
            ret.setCode(-1);
            ret.setMsg("合同已经签署过，不可重复签署");
            return ret;
        }

        BASE64Decoder decoder = new BASE64Decoder();
        try {
            String st = media.substring(22,media.length());
            System.out.println(st);
            byte[] b = decoder.decodeBuffer(media.substring(22,media.length()));

            // 处理数据
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            //String imgFilePath = "E:\\ZX\\file\\userFile\\new.png";
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String imgFilePath = ConstantsCode.FILE_PATH + "\\png\\"+uuid+".png";
            OutputStream out = new FileOutputStream(imgFilePath);

            out.write(b);
            out.flush();
            out.close();

            //File file = new File(ConstantsCode.FILE_PATH + "\\png\\"+uuid+".png");

            spin(imgFilePath,imgFilePath,-90);
            BFile bFile = new BFile();
            bFile.setFileId(uuid);
            bFile.setFileBelong(ConstantsCode.FILE_MODE);
            bFile.setFilePath("png"+"/"+uuid+".png");
            bFile.setFileMinitype("image/jpeg");
            bFile.setFileCreatetime(new Date());
            bFileService.insert(bFile);

            // 修改合同表状态

            record.setType(1);
            record.setSignPath(bFile.getFileId());
            contractService.updateByPrimaryKeySelective(record);
            //重新生成合同
            Ret reallyPath = createCon(record.getId(),Integer.parseInt(record.getOrgCode()));
            record.setReadPath(reallyPath.getMsg());
            contractService.updateByPrimaryKeySelective(record);

            return new Ret(0, bFile.getFileId());
        } catch (Exception e) {
            return new Ret(-1,"失败");
        }
    }

    /**
     * 生成合同
     * @param id 合同id
     * @param orgId 组织id
     * @return
     */
    public Ret createCon(Integer id, Integer orgId){
        Contract contract = contractService.selectByPrimaryKey(id);
        //找到模板
        ContractPath contractPath = contractPathService.selectByPrimaryKey(Integer.parseInt(contract.getConId()));
        //找出file表环境
        BFile data = bFileService.selectByPrimaryKey(contractPath.getFilePath());
        if(null == contractPath){
            return new Ret(-1,"内容不存在");
        }

        //查询是否已经生成合同
        //if(StringUtil.isBlank(contract.getReadPath())){
        //没有生成
        System.out.println("***********开始生成合同文件");
        BFile bFile = new BFile();
        bFile.setFileId(UUID.randomUUID().toString().replaceAll("-",""));
        bFile.setFileBelong(data.getFileBelong());
        bFile.setFilePath("zip"+"/"+ bFile.getFileId()+".docx");
        bFile.setFileMinitype(data.getFileMinitype());
        bFile.setFileName(contract.getName() + "-" + data.getFileName());
        bFile.setFileState(data.getFileState());
        bFileService.insert(bFile);
        //}

        ContractEx record = contractService.selectDetail(contract.getId());


        Map<String, Object> params = new HashMap<>();
//			ImageEntity image = new ImageEntity(img,50,50);
//			params.put("img",image);//印章
        BFile imgFile = bFileService.selectByPrimaryKey(contract.getYzPath());
        String path2 = ConstantsCode.FILE_PATH + imgFile.getFilePath();
        byte[] img = FileUtil.readBytes(path2);
        ImageEntity image = new ImageEntity(img,50,50);
        params.put("img",image);//印章

        //判断用户是否已经签名
        if(0 != contract.getType() && 3 != contract.getType()){
            BFile imgFile2 = bFileService.selectByPrimaryKey(contract.getSignPath());
            String userSign = ConstantsCode.FILE_PATH + imgFile2.getFilePath();
            byte[] userSignImg = FileUtil.readBytes(userSign);
            ImageEntity userSign2 = new ImageEntity(userSignImg,50,50);
            params.put("userSign",userSign2);//用户签名
        }else{
            params.put("userSign","待签名");
        }
        params.put("name",record.getName());//乙方名称
        params.put("idCard",record.getIdCard());//乙方身份证
        params.put("today", DateUtil.dateToStr(new Date()).substring(0,10));

            params.put("orgName",record.getOrgName());//机构名称


            params.put("address",record.getAddress() == null? "" : record.getAddress());//乙方住址
            params.put("idAddress",record.getIdAddress() == null? "" : record.getIdAddress());//乙方户籍地址
            params.put("phone",record.getPhone() == null? "" : record.getPhone());//乙方联系电话
            params.put("cirName",record.getCirName() == null? "" : record.getCirName());//紧急联系人姓名
            params.put("cirPhone",record.getCirPhone() == null? "" : record.getCirPhone());//紧急联系人电话


            //正式合同开始时的起始
            params.put("joinYear",DateUtil.getYear(record.getJoinTime()));//合同开始年份
            params.put("joinMonth",DateUtil.getMonth(record.getJoinTime()));//合同开始月份
            params.put("joinDay",DateUtil.getDay(record.getJoinTime()));//合同开始日期
            //正式合同开始时的结束
            params.put("endYear",DateUtil.getYear(record.getEndTime()));//合同结束的年份
            params.put("endMonth",DateUtil.getMonth(record.getEndTime()));//合同结束的月份
            params.put("endDay",DateUtil.getDay(record.getEndTime()));//合同结束的日期
            //试用期结束时间
            //先找出合同开始时的日期时间加2个月
            Date testJoinEndDate = DateUtil.addMonth(record.getJoinTime(), HrConstants.contractTestMonth);

            params.put("testJoinEndYear",DateUtil.getYear(testJoinEndDate));//试用期结束年份
            params.put("testJoinEndMonth",DateUtil.getMonth(testJoinEndDate));//试用期结束月份
            params.put("testJoinEndDay",DateUtil.getDay(testJoinEndDate));//试用期结束日期
            params.put("job",record.getJob() == null? "":record.getJob());//乙方工作
            params.put("area",record.getCityName()+record.getPointName());//工作地点--城市名称+站点名称


        try{
            XWPFDocument out = WordExportUtil.exportWord07(ConstantsCode.FILE_PATH+data.getFilePath(),params);
            FileOutputStream outputStream = new FileOutputStream(ConstantsCode.FILE_PATH+bFile.getFilePath());

            out.write(outputStream);
            outputStream.close();
            System.out.println("*************合同生成结束");
        }catch (Exception e) {
            e.printStackTrace();
        }

        contract.setReadPath(bFile.getFileId());
        contractService.updateByPrimaryKeySelective(contract);
        return new Ret(1,contract.getReadPath());
    }


    public static void spin(String source,String dest,int degree) throws Exception {
        int swidth = 0; // 旋转后的宽度
        int sheight = 0; // 旋转后的高度
        int x; // 原点横坐标
        int y; // 原点纵坐标

        File file = new File(source);
        if (!file.isFile()) {
            throw new Exception("ImageDeal>>>" + file + " 不是一个图片文件!");
        }
        BufferedImage bi = ImageIO.read(file); // 读取该图片
        // 处理角度--确定旋转弧度
        degree = degree % 360;
        if (degree < 0)
            degree = 360 + degree;// 将角度转换到0-360度之间
        double theta = Math.toRadians(degree);// 将角度转为弧度

        // 确定旋转后的宽和高
        if (degree == 180 || degree == 0 || degree == 360) {
            swidth = bi.getWidth();
            sheight = bi.getHeight();
        } else if (degree == 90 || degree == 270) {
            sheight = bi.getWidth();
            swidth = bi.getHeight();
        } else {
            swidth = (int) (Math.sqrt(bi.getWidth() * bi.getWidth()
                    + bi.getHeight() * bi.getHeight()));
            sheight = (int) (Math.sqrt(bi.getWidth() * bi.getWidth()
                    + bi.getHeight() * bi.getHeight()));
        }

        x = (swidth / 2) - (bi.getWidth() / 2);// 确定原点坐标
        y = (sheight / 2) - (bi.getHeight() / 2);

        BufferedImage spinImage = new BufferedImage(swidth, sheight,
                bi.getType());
        // 设置图片背景颜色
        Graphics2D gs = (Graphics2D) spinImage.getGraphics();
        gs.setColor(Color.white);
        gs.fillRect(0, 0, swidth, sheight);// 以给定颜色绘制旋转后图片的背景

        AffineTransform at = new AffineTransform();
        at.rotate(theta, swidth / 2, sheight / 2);// 旋转图象
        at.translate(x, y);
        AffineTransformOp op = new AffineTransformOp(at,
                AffineTransformOp.TYPE_BICUBIC);
        spinImage = op.filter(bi, spinImage);
        File sf = new File(dest);
        ImageIO.write(spinImage, "png", sf); // 保存图片

    }

}
